package com.netpace.iem.umair.dal;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import com.netpace.iem.umair.model.Income;

public class IncomeMemory implements IIncomeDao {
	private List<Income> incomes;
	Connection conn;

	// Default constructor is for Main memory Db
	public IncomeMemory() {
		this.incomes = new ArrayList<Income>();
	}

	@Override
	public void insert(Income income){
		incomes.add(income);
	}
	
	@Override
	public void update(Income income, int pk) {
		int index = getIndex(pk); 
		if ( index != -1 ) {
			incomes.remove(index);
			incomes.add(index, income);
		}
	}
	
	@Override
	public void delete(Income income, int pk) {
		int index = getIndex(income); 
		if ( index != -1 ) {
			incomes.remove(index);
		}
	}
	
	@Override
	public void delete(int pk) {
		int index = getIndex(pk); 
		if ( index != -1 ) {
			incomes.remove(index);
		}
	}
	
	@Override
	public Income findById(int pk) {
		int index = getIndex(pk); 
		
		if ( index != -1 ) {
			return incomes.get(index);
		}
		
		return null;
	}
	
	@Override
	public List<Income> findAll(){
		return incomes;
	}
	
	private int getIndex(Income income) {
		if ( incomes.contains(income) ) 
			return incomes.indexOf(income);
		else
			return -1;
	}
	
	private int getIndex(int pk) {
		for (int i = 0; i < incomes.size(); i++) {
			if ( incomes.get(i).getId() == pk ) {
				return i;
			}
		}
		return -1;
	}
}
